/**  
 *	VisualGroup JavaScript prototype Classes, version 0.1
 *  (c) 2008 Bill Vison <vison_ruan@126.com>
 *
 *
/*--------------------------------------------------------------------------*/
using("Vsg");
using("Vsg.FlashHttpRequest");

Vsg.AuthorisingManager = Ext.extend(Ext.util.Observable,{
	
	_rules:null,
	
	_registedComponents:null,
	
	_registedUrls:null,
	
	_registedModule:null,
	
	// --- load the auth component defined ---
	_authUrls:null,
	
	_authComps:null,
	
	_loadUrl:null,

	constructor:function($config) {
		
		// ---- init variable ---
		this._rules = [];
		
		this._loadUrl = new Ext.util.MixedCollection();
		
		Vsg.AuthorisingManager.superclass.constructor.call(this, $config);
		
		this.addEvents({
        	"init" : true,
			"_loadauth":true,
			"ready" : true,
			"exception" : true
    	});
		
		this.on("init" , this._init);
		this.on("_loadauth" , this._loadAuthUrl);
	},
	
	regUrlCode:function($codeRef) {
		Ext.apply(this , $codeRef);
	},
	
	loadReady:function() {
		
		if (this._authComps != null && this._registedComponents != null) {
			return true;
		} else {
			return false;
		}
	},
	
	_loadAuthUrl:function($this) {
		
		//var $authUrls = "authorization/authz.json";
		var $authUrls = Vsg.getURLKey("_SECURITY-AUTHORIZATION");
		
		// load config object 
		var $actionConfig = {};
		$actionConfig.url = Vsg.getURLKey("_SECURITY-AUTHORIZATION");

		$actionConfig.method = "POST";
		$actionConfig.timeout = 30;
		$actionConfig.params = {module:this.module,code:this.code};
		$actionConfig.success = function($action , $option) {
			var $resObj = Ext.util.JSON.decode($action.responseText);
			$this._authUrls = $resObj.authUrls;
			$this._authComps = $resObj.authComponents;
			$this.hadLoad = true;
		}
		$actionConfig.failure = function($action , $option) {
			$this.hadLoad = false;
			throw new Vsg.AuthorisingManager.AuthorisingManagerException("occur in load authorization file!" , null , Vsg.AuthorisingManager.AuthorisingManagerException.LoadAuthorisingFail);				
		}
		
		Vsg.FlashHttpRequest.request($actionConfig);			

	},
	
	_init:function($this) {
		
	},
	
	/**
	 * check find the components by id
	 * @param {string} $id
	 */
	_findAuthComponentsById:function($id) {
		var $comps = [];
		var $comp = null;
		if (this._authComps != undefined) {
			for (var $i = this._authComps.length - 1 ; $i >=0 ; $i--) {
				$comp = this._authComps[$i];
				if ($comp.id == $id) {
					$comps.push( $comp );
				}
			}			
		}

		return $comps;
	},
	
	_findRuleByXtype:function($xtype) {
		var $rules = [];
		for (var $i = 0; $i < this._rules.length; $i++) {
			if (this._rules[$i].xtype == $xtype) {
				$rules.push( this._rules[$i] );
			}
		}
		return $rules;
	},
	
	
	_findAuthControlById:function($id) {
		var $control = null;
		for (var $i = 0 ; $i < this._authComps.length ; $i++) {
			if ($id == this._authComps[$i].id) {
				$control = this._authComps[$i].controller;
				break;
			}
		}
		return $control;
	},
	
	addRule:function($ruleClass) {
		// ---detect rule
		var $rule = null;
		try {
			if (this._rules.indexOf($ruleClass) == -1) {
				this._rules.push($ruleClass);
			}
		} catch (ex) {
			Ext.log(ex);
		} finally {
			$rule = null;
		}

	},
	
	
	authorized:function() {
		this.fireEvent("_loadauth" , this);
		var $this = this
		// --- run the authorized method ---

		var $intervalId = setInterval(function() {
			var $break = 0;
			if ($this.hadLoad != undefined ) {
				$break = 1;
			}
			
			if ($break) {
				clearInterval($intervalId);
				// --- invoke execute rule ,fire event after current page ----
				$this._processRule();
			}
		},30);	

		
	},
	
	_processRule:function() {
		// execute rule
		try {
			var $pass = true;
			for(var $i = 0 ; $i < this._rules.length ; $i++) {
				var $rule = new this._rules[$i]();
				try {
					$rule.fireEvent("afterLoadUrl" ,  this._authUrls);
				} catch ( ex ) {
					if (ex instanceof Vsg.AuthorisingRule.RuleException) {
						error(ex.getMessage());
						if (!$rule.chkResult() ) {
							$pass = false;
						}						
					} else {
						throw ex;
					}
				}
			}
			if ($pass) {
				this.fireEvent("ready" , this);
			}
		} catch (ex) {
			this.fireEvent("exception" , ex , this);
		};

	},
	
	/**
	 * That means defined component 
	 * @param component defined the original defined
	 * @param {string} defined id
	 */
	makeAuthorisingComponent:function($component , $id , $sub) {
		
		// --- search component id from authorising file ---
		var $authComps = this._findAuthComponentsById($id);
		// --- find the component rule by xtype ---
		var $xtype = $component.xtype != null ? $component.xtype : "";

		var $compXtypes = this._findRuleByXtype($xtype);

		// --- build the rules ----
		if ($compXtypes.length > 0) {
			var $rule = null;
			for (var $i = 0 ; $i < $compXtypes.length ; $i++) {
				$rule = new $compXtypes[$i]();
				try {
					$rule.setAuthComponents( this._authComps );
					$rule.fireEvent("genComp" , $component , $id , $sub);
					return $rule.chkResult();
				} catch (ex) {
					if (ex instanceof Vsg.AuthorisingManager.AuthorisingManagerException) {
						Ext.log(ex.getLocalMessage());
					} else {
						Ext.log("出现未知错误: " + ex);
					}					
				}
			}
		}
		return null;
	}
							  
});

Vsg.AuthorisingManager.AuthorisingManagerException = Ext.extend(Exception.CommonException,{
	name:"Vsg.AuthorisingManager.AuthorisingManagerException",
	constructor:function($message , $name ,$value) {
		Vsg.AuthorisingManager.AuthorisingManagerException.superclass.constructor.apply(this, arguments);
	}
});
Vsg.AuthorisingManager.AuthorisingManagerException.CreateManagerError = 1;
Vsg.AuthorisingManager.AuthorisingManagerException.NoSetRegisterFile = 2;
Vsg.AuthorisingManager.AuthorisingManagerException.LoadRegisterFileFail = 3;
Vsg.AuthorisingManager.AuthorisingManagerException.LoadAuthorisingFail = 5;
Vsg.AuthorisingManager.AuthorisingManagerException.NotFoundRegistedComponent = 4;
Vsg.AuthorisingManager.AuthorisingManagerException.NotDefinedAuthorisingURL = 6;
Vsg.AuthorisingManager.AuthorisingManagerException.NotDefinedAuthorisingComponents = 7;